#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2023/4/14 15:56
# @Author  : jiangwei
# @Site    : 
# @File    : login_jddj_playwright.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

import time
import logging
from PIL import Image
from playwright.sync_api import Playwright, sync_playwright, expect

from jddj.login.ddd_verify_code import ddddocr_verify_code
from pipeline.cookie_sql import MySqlDB
# from utils.sendmail import execute_send_jddj_mail
# from common.config import PLAYWRIGHT_WEBDRIVER_PATH
from apscheduler.schedulers.blocking import BlockingScheduler

logging.getLogger('PIL.PngImagePlugin').setLevel(logging.ERROR)
logging.getLogger('asyncio').setLevel(logging.ERROR)

WEBDRIVER_PATH = ""


def try_verify_code(page, try_count=0):
    # 3 执行验证码识别
    img_ele = page.query_selector("div[class='img-code-wrap']")
    img_ele.screenshot(path="./jddj_verify.png")
    im = Image.open('./jddj_verify.png')
    im.save('jddj_code_verify.png')
    # yzm = base64_api("./jddj_code_verify.png")
    yzm = ddddocr_verify_code('./jddj_code_verify.png')
    print("---yzm---", yzm)
    code_ele = page.query_selector("input[name='imgCerificatCode']")
    code_ele.fill(yzm)
    time.sleep(7)
    print("【验证码输入】成功")

    button_ele = page.query_selector("button[type='button']")
    button_ele.click()
    print("【点击登录】成功")
    time.sleep(5)
    login_failed_ele = page.query_selector("div[class='error-tip']")
    if login_failed_ele:
        error = login_failed_ele.inner_text()
        print("==error==", error)
        if "图片验证码错误" in error:
            try_count += 1
            try_verify_code(page=page, try_count=try_count)
        if "手机" in error:
            time.sleep(60 * 10)

    else:
        return page


def run(playwright: Playwright) -> None:
    """
    【京东到家】执行登录
    :param playwright:
    :return:
    """
    # https://store.jddj.com/  京东到家需求  jd_mcyp	mcyp2019!!@	张伟宗
    # try:
    m = MySqlDB()
    cookies = ''

    user = "jd_mcyp"
    pwd = "mcyp2019!!@"
    browser = playwright.chromium.launch(headless=False, executable_path=WEBDRIVER_PATH)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://store.jddj.com/")
    time.sleep(5)

    # 1 输入账号
    uname_ele = page.query_selector("input[name='loginName']")

    uname_ele.fill(user)
    time.sleep(3)
    print("【输入账号：{}】成功".format(user))

    # 2 输入密码
    pwd_ele = page.query_selector("input[name='password']")
    pwd_ele.fill(pwd)
    time.sleep(3)
    print("【输入密码:{}】成功".format(pwd))

    # 3 执行验证码识别
    img_ele = page.query_selector("div[class='img-code-wrap']")
    img_ele.screenshot(path="./jddj_verify.png")
    im = Image.open('./jddj_verify.png')
    im.save('jddj_code_verify.png')
    # yzm = base64_api("./jddj_code_verify.png")
    yzm = ddddocr_verify_code('./jddj_code_verify.png')
    print("---yzm---", yzm)
    code_ele = page.query_selector("input[name='imgCerificatCode']")
    code_ele.fill(yzm)
    time.sleep(7)
    print("【验证码输入】成功")

    button_ele = page.query_selector("button[type='button']")
    button_ele.click()
    print("【点击登录】成功")
    time.sleep(5)

    login_failed_ele = page.query_selector("div[class='error-tip']")
    if login_failed_ele:
        error = login_failed_ele.inner_text()
        print("==error==", error)
        if "图片验证码错误" in error:
            try_verify_code(page=page)

        if "手机" in error:
            time.sleep(60 * 5)
        # print("登陆失败")
        # m.insert_jddj_cookie(id=53, user_name="JDDJ_{}".format(user),
        #                      password=pwd, cookies="", _scm_token_="")
        # print("cookie存储sql结束")
    else:
        print("登录成功")
        cookie_list = context.cookies()

        for cookie in cookie_list:
            # print("-----", cookie)
            str_cookie = '{0}={1};'
            if cookie.get('name') == "user":
                print("====USER====")
                print(cookie)
                print("====USER====")
                str_cookie = str_cookie.format(cookie.get('name'), cookie.get('value'))
                cookies += str_cookie

        # Close page
        m.insert_jddj_cookie(id=53, user_name="JDDJ_{}".format(user),
                             password=pwd, cookies=cookies, _scm_token_="")
        print("cookie存储sql结束")

    page.close()
    context.close()
    browser.close()
    m.close()

    print("登录执行结束")

    # except Exception as e:
    #     execute_send_jddj_mail(success=False, content="使用playwright执行京东到家登录失败", msg="登录异常，请重新执行登录")


def login_for_cookie(TRY_COUNT=0):
    """
    执行登录存入cookie
    :return:
    """
    print("*************** 第{}次登录开始 ***************".format(TRY_COUNT))
    with sync_playwright() as playwright:
        run(playwright)
    print("*************** 第{}次登录结束 ***************".format(TRY_COUNT))

    m = MySqlDB()
    user = "jd_mcyp"
    cookie_in_sql = m.get_cookie(user_name="JDDJ_{}".format(user))
    cookie = cookie_in_sql[0] if cookie_in_sql else ""

    if cookie:
        m.close()
        return cookie

    else:
        TRY_COUNT += 1
        if TRY_COUNT > 10:
            m.close()
            print("重试十次登录依然失败")
            return False

        login_for_cookie(TRY_COUNT=TRY_COUNT)


def save_cookie_only(cookies):
    """
    存储cookie，只需要cookie中key为user这个key的cookie值
    :param cookies:
    :return:
    """
    m = MySqlDB()
    user = "jd_mcyp"
    pwd = "mcyp2019!!@"
    m.insert_jddj_cookie(id=53, user_name="JDDJ_{}".format(user),
                         password=pwd, cookies=cookies, _scm_token_="")
    print("cookie存储sql结束")
    m.close()


if __name__ == '__main__':
    # login_for_cookie()
    # https://store.jddj.com/frame/1032/2909  登录过期，可以先本地电脑手动执行下登录，如果登录未出验证码，直接到结算管理那边的对账单查询拿接口的cookie
    cookies = 'user=3X6G3XZ3FUU4B74FEZNCUF5UUGVDXCVOHPO4AUV6FVOZPN46T7VZW276UDXLDQCN7MLXBMG5KFKDLEQU7TQA4BVKSR2SANET56YFEPMAA7B3JGKZY7NOYXTVYNO7QQQ75ZDN7JWOKBRC5IPCH3KJ76D3OLGZMTHJ5KZQXE5RWAVXGWX63IHSTYBAWMNOWM5AZB5DADGWI6QXS5ALCOBMRXD3LYL674NWDQXS2KOCUJEPP6FAX3QIADCW63IY22AU5YLBGHCTY2M4USBTQSPG23WZYJGSOZRXRC4MTDLZQ4XGNDWIBED52MSI4D2K6KERATYLEELRXLM2XUGVFZRDTO7KFV53OS2Z7WRRZKVFWUAKGEX7L6S3NIJNKFQJ7AMB'
    save_cookie_only(cookies=cookies)

# scheduler = BlockingScheduler()
# scheduler.add_job(func=login_for_cookie, trigger='cron', day_of_week="2", hour="8", minute="15", timezone='Asia/Shanghai', misfire_grace_time=60)  # 检查数据入库量
# scheduler.start()
